package org.blogwu.learn.algorithm.栈;

public class Stack<E> {

    private int size = 0;

    // 栈顶
    private Node<E> topNode;


    private static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }

        public E getElement() {
            return element;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setElement(E element) {
            this.element = element;
        }
    }

    public int getSize() {
        return size;
    }


    /**
     * 压栈
     *
     * @param e
     */
    public void push(E e) {
        Node<E> eNode = new Node<>(e, null);
        if (topNode != null) {
            eNode.setNext(topNode);
        }
        topNode = eNode;
        size++;
    }

    /**
     * 出栈
     *
     * @return
     */
    public E pop() {
        if (topNode == null || size == 0) {
            return null;
        }
        size--;
        E e = topNode.getElement();
        if (topNode.getNext() == null) {
            topNode.setNext(null);
            topNode.setElement(null);
        } else {
            Node<E> nextNode = topNode.getNext();
            topNode = nextNode;
        }
        return e;
    }
}
